﻿using DotNetCore.CAP;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace Leo.Common.CAP
{
    /// <summary>  
    /// 服务注册 扩展  
    /// </summary>  
    public static class ServiceCollectionExtensions
    {
        public static CapBuilder AddCAP(this IServiceCollection services, IConfiguration configuration = null, Action<CapOptions> action = null)
        {
            // 添加 CAP 服务  

            var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembiy => assembiy.GetTypes())
               .Where(r => r.IsClass && r.IsPublic && typeof(IDealQueueHandler).IsAssignableFrom(r)).ToList();

            foreach (var type in types)
            {
                services.AddSingleton(type);
            }

            services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(AppDomain.CurrentDomain.GetAssemblies()));

            return services.AddCap(CAPConfigurators.Init(configuration, action));

        }
    }
}
